package pt.fct.mpc.lastfm.connectivity.bt;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;

import android.util.Log;

public class LastfmBluetoothInputStream
	extends InputStream
{
	private static final String TAG = "Last.fm BT InputStream";
	
	private boolean reached_end = false;
	
	private int total_bytes;
	private int received_bytes;
	
	private InputStream is;
	private DataInputStream data_input;

	private ByteArrayInputStream byte_array;
	
	public LastfmBluetoothInputStream(InputStream is) 
		throws IOException
	{
		this.is = is;
		this.data_input = null;
		this.received_bytes = 0;
	}
	
	@Override
	public int read(byte[] b, int offset, int length)
		throws IOException
	{
		initStream();
		
		if (reached_end)
			return -1;
		
		int read_bytes = this.byte_array.read(b, offset, length);
	
		Log.d(TAG, "Just read "+read_bytes+" bytes: still "
			+this.byte_array.available() + " available of "
			+this.total_bytes+" total");

		if (read_bytes != -1)
		{
			this.received_bytes += read_bytes;
		}
		
		if (this.byte_array.available() <= 0)
			this.reached_end = true;
		
		if (this.received_bytes >= this.total_bytes)
			this.reached_end = true;
		
		return read_bytes;
	}
	
	@Override
	public int read(byte[] b)
		throws IOException
	{
		return this.read(b, 0, b.length);
	}

	@Override
	public int read()
		throws IOException
	{
		initStream();
		int byte_read = this.byte_array.read();
		if (byte_read > -1)
			this.received_bytes ++;
		
		return byte_read;
	}

	private void initStream() 
		throws IOException
	{
		if (this.data_input != null)
			return;
		
		this.data_input = new DataInputStream(this.is);
		this.total_bytes = this.data_input.readInt();
		
		ByteArrayOutputStream tmp_data = 
			new ByteArrayOutputStream(this.total_bytes);
		
		int tmp_read_bytes = 0;
		while (tmp_read_bytes < this.total_bytes)
		{
			byte[] data = new byte[1024];
			
			for (int i = 0; i < data.length; i ++)
				data[i] = (byte) 0;
			
			int tmp = this.data_input.read(data);
			
			tmp_data.write(data, 0, tmp);
			
			if (tmp > -1)
				tmp_read_bytes += tmp;
		}
		
		byte[] data = tmp_data.toByteArray();
		this.byte_array = new ByteArrayInputStream(data);
	}

}
